package com.asiainfo.simpledao;

import java.util.Map;

import javax.sql.DataSource;

public class OracleDao extends AbstractDao {

	public OracleDao(DataSource dataSource) {
		super(dataSource);
	}

	public OracleDao(String url, String user, String password) {
		super(url, user, password);
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	@Override
	public Page selectList(String sql, int currPage, int pageSize, Object... params) {
		int count = count(sql, params);
		Page page = new Page();
		page.setCurrPage(currPage);
		page.setPageSize(pageSize);
		page.setTotal(count);
		int startRow = (currPage - 1) * pageSize;
		page.setRows(selectList(getPageSql(sql, startRow < 0 ? 0 : startRow, pageSize), params));
		return page;
	}

	private String getPageSql(String sql, int startRow, int size) {
		return String.format("SELECT * FROM (SELECT ROW_.*, ROWNUM ROWNUM_ FROM (%s) ROW_ WHERE ROWNUM <= %d) WHERE ROWNUM_ > %d",
				//
				sql, startRow + size, startRow);
	}

	@Override
	public Page selectList(String sql, int currPage, int pageSize, Map<String, Object> params) {
		int count = count(sql, params);
		Page page = new Page();
		page.setCurrPage(currPage);
		page.setPageSize(pageSize);
		page.setTotal(count);
		int startRow = (currPage - 1) * pageSize;
		page.setRows(selectList(getPageSql(sql, startRow < 0 ? 0 : startRow, pageSize), params));
		return page;
	}

}
